package com.example.library_base.base

import androidx.lifecycle.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

abstract class BaseViewModel<M : BaseModel>: ViewModel(), LifecycleObserver {
    private var mModelLiveData: MutableLiveData<M> = MutableLiveData<M>()

    fun getModelLiveData(): LiveData<M> {
        return mModelLiveData
    }

    fun setModelLiveData(value: M){
        mModelLiveData.postValue(value)
    }

    fun launchUI(block: suspend CoroutineScope.() -> Unit) = viewModelScope.launch {
        try {
            block()
        }catch (e: Exception){
            e.printStackTrace()
        }
    }

    fun launchIO(block: suspend CoroutineScope.() -> Unit) = viewModelScope.launch {
        withContext(Dispatchers.IO){
            try {
                block()
            }catch (e: Exception){
                e.printStackTrace()
            }
        }
    }

}